package com.lac.component.controller;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import com.lac.component.dao.GoodsSpuTraceSourceMapper;

import com.lac.component.model.GoodsSpuTraceSource;
import com.lac.component.utils.OSSUrlUploader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * @author xiaokuixiao
 * date2025/7/30 16:14
 */
@RestController
@Slf4j
public class GoodsSpuTraceSourceController {
    @Autowired
    private GoodsSpuTraceSourceMapper goodsSpuTraceSourceMapper;

    @GetMapping("/content")
    public String draftJson() {
        StringBuffer combinedSql = new StringBuffer();
        StringBuffer deleteCombinedSql = new StringBuffer();
        List<GoodsSpuTraceSource> pageGoodsSpuTraceSources = goodsSpuTraceSourceMapper.getPageGoodsSpuTraceSource();
//        pageGoodsSpuTraceSources = pageGoodsSpuTraceSources.stream().limit(3).collect(Collectors.toList());
        List<String> idList = new ArrayList<>();
        List<String> serverNamesMutable = new ArrayList<>(Arrays.asList("wm-dev-b1", "wm-prod-b1", "em-dev-b1", "em-prod-b1","https://siwmstatic.ecej.com"));        // 遍历所有需要处理的商品，或者只处理第一个/特定id的
        // 这里只是示例，通常你会有一个循环
        String url = "wm-prod-b1.oss-cn-beijing.aliyuncs.com/common/video";
        String imageUrl = "https://wm-prod-b1.oss-cn-beijing.aliyuncs.com/common/material";
        for (int i = 0; i < pageGoodsSpuTraceSources.size(); i++) {
            GoodsSpuTraceSource goodsSpuTraceSource = pageGoodsSpuTraceSources.get(i);
            String OldContent = goodsSpuTraceSource.getContent();
            String newContent = checkAndReuploadResources(OldContent, serverNamesMutable);
            String OldPicUrls = goodsSpuTraceSource.getPicUrls();
            String newPicUrls = checkAndReuploadPicUrls(OldPicUrls, serverNamesMutable);

            // 比较新旧JSON字符串，避免不必要的更新
            if ((!newContent.equals(OldContent) || newContent.contains(url) || newContent.contains(imageUrl)) && (!newPicUrls.equals(OldPicUrls) || newPicUrls.contains(url) || newPicUrls.contains(imageUrl))) {
                String goodsSpuId = goodsSpuTraceSource.getId().replace("'", "''"); // 简单的单引号转义

                String updateSql = String.format(
                        "UPDATE `oms_mall`.`goods_spu_trace_source` SET `%s` = '%s' , `%s` = '%s' WHERE  `id` = '%s';",
                        "content", newContent, "pic_urls", newPicUrls,
                        goodsSpuId
                );
                // 构建SQL更新语句
//                String updateSql = buildUpdateSql(goodsSpuChannel.getId(), newDraftJson, "draft_json");

                combinedSql.append(updateSql).append("\n");

                String deleteSql = buildDeleteSql(goodsSpuTraceSource.getId());

                deleteCombinedSql.append(deleteSql).append("\n");
            } else if ((!newContent.equals(OldContent) || newContent.contains(url) || newContent.contains(imageUrl)) && newPicUrls.equals(OldPicUrls)) {
                String updateSql = buildUpdateSql(goodsSpuTraceSource.getId(), newContent, "content");

                combinedSql.append(updateSql).append("\n");

                String deleteSql = buildDeleteSql(goodsSpuTraceSource.getId());

                deleteCombinedSql.append(deleteSql).append("\n");
            } else if (newContent.equals(OldContent) && (!newPicUrls.equals(OldPicUrls) || newPicUrls.contains(url) || newPicUrls.contains(imageUrl))) {
                String updateSql = buildUpdateSql(goodsSpuTraceSource.getId(), newPicUrls, "pic_urls");

                combinedSql.append(updateSql).append("\n");

                String deleteSql = buildDeleteSql(goodsSpuTraceSource.getId());

                deleteCombinedSql.append(deleteSql).append("\n");
            } else {
                idList.add(goodsSpuTraceSource.getId());
                System.out.println("GoodsSpu ID: " + goodsSpuTraceSource.getId() + " 的图片URL没有变化，无需更新。");
            }
            log.info("条数============================================={}", i + 1);
        }
        log.info("combinedSql:{}", combinedSql);
        if (idList.size() > 0) {
            String goodsSpuId = String.join(",", idList);
            String selectSql = "SELECT * FROM `oms_mall`.`goods_spu_channel` WHERE `id` IN (" + goodsSpuId + ");";
            String string = combinedSql.append(deleteCombinedSql).append(selectSql).toString();
            log.info("selectSql:{}", string);
            return string;
        } else {
            String string = combinedSql.append(deleteCombinedSql).toString();
            log.info("selectSql:{}", string);
            return string;
        }
    }


    public static String checkAndReuploadPicUrls(String picUrlsJson, List<String> serverNames) {
        Gson gson = new Gson();
        Type listType = new TypeToken<List<String>>() {
        }.getType();
        List<String> urlList = null;
        try {
            urlList = gson.fromJson(picUrlsJson, listType);
        } catch (Exception e) {
            log.error(" picUrls JSON失败: {}, JSON: {}", e.getMessage(), picUrlsJson);
        }
        // 存储新生成的OSS URL
        List<String> ossUrls = new ArrayList<>();
        boolean hasAnyUrlUploaded = false; // 标记是否有任何一个URL成功上传

        if (urlList != null && !urlList.isEmpty()) { // 确保urlList不为null且不为空
            for (String picUrl : urlList) {
                String ossUrl = null;
                boolean isUploaded = false;
                for (String serverName : serverNames) {
                    if (picUrl.contains(serverName)) {
                        isUploaded = true;
                    }
                }
                if (StringUtils.isNotBlank(picUrl) && !isUploaded) {
                    try {
                        ossUrl = OSSUrlUploader.uploadFromUrlWithSnowflakeName(picUrl, "common/material");
                        if (StringUtils.isNotBlank(ossUrl)) {
                            ossUrls.add(ossUrl);
                            hasAnyUrlUploaded = true;
                        } else {
                            // 如果上传返回空，保留原URL以防止数据丢失，或者记录错误
                            log.warn("图片 {} 上传到OSS返回空URL，将保留原URL。", picUrl);
                            ossUrls.add(picUrl); // 保持原有的URL
                        }
                    } catch (Exception e) {
                        log.error("上传图片异常{},原始URL:{},错误信息:{}", e.getClass().getSimpleName(), picUrl, e.getMessage());
                        // 如果上传失败，保留原始URL，避免数据丢失
                        ossUrls.add(picUrl);
                    }
                } else {
                    // 如果原始URL是空白的，也加入到新列表中，保持数组结构
                    ossUrls.add(picUrl);
                }
            }
        }
        // 只有当有图片成功上传或列表结构发生变化时才更新
        // 确保即使所有上传都失败，但是原始picUrls存在，我们也会生成一个新的JSON字符串 (可能包含原始URL)
        String newPicUrlsJson = gson.toJson(ossUrls);
        return newPicUrlsJson;
    }

    /**
     * 检查并重新上传图片到OSS
     * @param htmlContent 包含图片URL的HTML内容
     * @param serverNames 需要重新上传的服务器名称列表
     * @return 更新后的HTML内容
     */
    /**
     * 检查并重新上传图片到OSS
     *
     * @param htmlContent 包含图片URL的HTML内容
     * @param serverNames 需要重新上传的服务器名称列表
     * @return 更新后的HTML内容
     */
    public static String checkAndReuploadResources(String htmlContent, List<String> serverNames) {
        if (StringUtils.isBlank(htmlContent)) {
            return htmlContent;
        }

        // 同时匹配img和video标签的src属性
        String regex = "<(img|video)[^>]+?src\\s*=\\s*[\"']?([^\"'\\s>]+)[\"']?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(htmlContent);
        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String fullTag = matcher.group(0);   // 完整标签
            String tagType = matcher.group(1);    // 标签类型（img或video）
            String resourceUrl = matcher.group(2); // 资源URL

            log.info("处理{}标签: {}, URL: {}", tagType, fullTag, resourceUrl);

            // 检查是否需要重新上传
            boolean needReupload = false;
            for (String serverName : serverNames) {
                if (resourceUrl.contains(serverName)) {
                    log.info("URL 包含 serverName {}, 不重新上传", serverName);
                    needReupload = true;
                    break;
                }
            }

            String newResourceUrl = resourceUrl;
            if (!needReupload && StringUtils.isNotBlank(resourceUrl) && resourceUrl.startsWith("http")) {
                try {
                    // 根据资源类型选择上传目录
                    String uploadPath = "img".equals(tagType)
                            ? "common/material"
                            : "common/video";

                    newResourceUrl = OSSUrlUploader.uploadFromUrlWithSnowflakeName(resourceUrl, uploadPath);
                } catch (Exception e) {
                    log.error("重新上传{}失败: {}", tagType, resourceUrl, e);
                }
            } else {
                log.info("跳过处理: needReupload={}, isHttp={}", needReupload, resourceUrl.startsWith("http"));
            }

            // 替换标签中的URL
            String newTag = fullTag.replace(resourceUrl, newResourceUrl);
            matcher.appendReplacement(result, Matcher.quoteReplacement(newTag));
            log.info("替换后的{}标签：{}", tagType, newTag);
        }
        matcher.appendTail(result);
        return result.toString();
    }


    /**
     * 构建SQL UPDATE语句的辅助方法
     *
     * @param goodsSpuId     商品ID
     * @param newPicUrlsJson 新的图片URL JSON字符串
     * @return SQL UPDATE语句
     */
    private String buildUpdateSql(String goodsSpuId, String newPicUrlsJson, String featureName) {
        // 注意：实际生产环境中，请使用PreparedStatement防止SQL注入！
        // 这里的拼接仅用于演示生成的SQL字符串。

        // 为了SQL安全，需要对newPicUrlsJson进行适当的转义，特别是单引号
        // 通常数据库驱动或ORM框架会自动处理
        String escapedNewPicUrlsJson = newPicUrlsJson.replace("'", "''"); // 简单的单引号转义
        goodsSpuId = goodsSpuId.replace("'", "''"); // 简单的单引号转义

        return String.format(
                "UPDATE `oms_mall`.`goods_spu_trace_source` SET `%s` = '%s' WHERE `id` = '%s';",
                featureName, escapedNewPicUrlsJson,
                goodsSpuId
        );
    }

    /**
     * 构建SQL DELETE语句的辅助方法
     *
     * @param goodsSpuId 商品ID
     * @return SQL DELETE语句
     */
    private String buildDeleteSql(String goodsSpuId) {
        return String.format("DELETE FROM `oms_mall`.`goods_spu_trace_source` WHERE `id` = %s;", "'" + goodsSpuId + "'");
    }


}
